package com.tianyi.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author tianyi
 * @Description 对redis的操作进行封装
 * @Date 2022 - 10 - 30
 **/
@Component
public class RedisOperate {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 加锁
     * @param key 字段名称
     * @param value 字段的值
     * @param timeout 超时时间
     * @param timeUnit ？
     * @param <T>
     */
    public <T> void setOperateValue(final String key, final T value, final Integer timeout, final TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     *  写入缓存并设置有效时间
     * @param key 键
     * @param value 值
     * @param expireTime 过期时间
     * @return 返回是否成功
     * @param <T> 对象类型
     */
    public <T> boolean setEx(final String key , final T value , int expireTime){
        boolean result = false;
        try{
            ValueOperations<String ,Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
            result = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 判断缓存中是否有对应的key
     * @param key 键
     * @return 是否有值
     */
    public boolean exists(final String key){
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取值
     * @param key 键
     * @return 结果
     * @param <T> 结果对象
     */
    public <T> T get(final String key){
        ValueOperations<String , T> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    /**
     * 删除对应的键值
     * @param key 键
     * @return 返回
     */
    public boolean remove(final String key){
        if(exists(key)){
            return redisTemplate.delete(key);
        }
        return false;
    }
    /**
     *
     * @param key
     * @return
     * @param <T>
     */
    public <T> T getOperateValue(final String key){
        ValueOperations<String , T> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

}
